<template>
  <div>
    <van-nav-bar title="更换手机" left-arrow @click-left="backUp"></van-nav-bar>
    <div class="register">
      <van-cell-group>
        <van-field
          type="tel"
          placeholder="请输入原手机号码"
          label="原手机号码"
          v-model="data.mobile"
          :error-message="errorMsg.mobile"
          clearable
        ></van-field>
        <van-field
          center
          v-model="data.code"
          label="短信验证码"
          placeholder="请输入验证码"
          :error-message="errorMsg.code"
          clearable
        >
          <van-button
            slot="button"
            size="small"
            type="danger"
            :disabled="countdown > 0"
            @click="sendMobileCode"
          >{{ countdown ? countdown + 's' : '发送'}}</van-button>
        </van-field>
      </van-cell-group>
      <van-cell-group>
        <van-field
          type="tel"
          placeholder="请输入新手机号码"
          label="新手机号码"
          v-model="data.mobile"
          :error-message="errorMsg.mobile"
          clearable
        ></van-field>
        <van-field
          center
          v-model="data.code"
          label="短信验证码"
          placeholder="请输入验证码"
          :error-message="errorMsg.code"
          clearable
        >
          <van-button
            slot="button"
            size="small"
            type="danger"
            :disabled="countdown > 0"
            @click="sendMobileCode"
          >{{ countdown ? countdown + 's' : '发送'}}</van-button>
        </van-field>
      </van-cell-group>
      <div class="register-btn">
        <van-button block type="danger" @click.stop="goRegister">保存</van-button>
      </div>
    </div>
  </div>
</template>
<script>
// import {Field, CellGroup, Cell, Button, Toast} from 'vant';
import { Field, Icon, Button, Cell, CellGroup, NavBar, Toast } from "vant";

import validator from "@/utils/validation.js";
import url from "@/utils/api.js";

export default {
  name: "phonechange",
  components: {
    [Field.name]: Field,
    [Icon.name]: Icon,
    [Button.name]: Button,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [NavBar.name]: NavBar,
    [Toast.name]: Toast
  },
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.data.pwd) {
        callback(new Error("两次输入密码不一致"));
      } else {
        callback();
      }
    };
    return {
      countdown: 0,
      data: {
        name: "",
        mobile: "",
        code: "",
        pwd: "",
        password2: "",
        address: "",
        company: ""
      },
      errorMsg: {
        mobile: "",
        name: "",
        pwd: "",
        password2: "",
        address: "",
        company: ""
      },
      rules: {
        name: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback("真实姓名不能为空");
              } else if (/[\u4e00-\u9fa5]/g.test(value)) {
                callback();
              } else {
                callback("请输入中文真实姓名");
              }
            },
            trigger: "blur"
          }
        ],
        address: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback("收货地址不能为空");
              } else if (/[\u4e00-\u9fa5]/g.test(value)) {
                callback();
              } else {
                callback("请输入中文收货地址");
              }
            },
            trigger: "blur"
          }
        ],
        company: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback("公司名称不能为空");
              } else if (/[\u4e00-\u9fa5]/g.test(value)) {
                callback();
              } else {
                callback("请输入中文公司名称");
              }
            },
            trigger: "blur"
          }
        ],
        mobile: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                callback("手机号码不能为空");
              } else if (/^[1][3-9][0-9]{9}$/.test(value)) {
                callback();
              } else {
                callback("请输入正确的手机号码");
              }
            },
            trigger: "blur"
          }
        ],
        code: [{ required: true, message: "请输入验证码" }],
        pwd: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { min: 6, max: 30, message: "长度在 6 到 30 个字符", trigger: "blur" }
        ],
        password2: [
          { required: true, message: "确认密码不能为空", trigger: "blur" },
          {
            min: 6,
            max: 30,
            message: "长度在 6 到 30 个字符",
            trigger: "blur"
          },
          { validator: validatePass2, trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    backUp() {
      this.$router.go(-1);
    },
    goRegister() {
      this.validate((errors, fields) => {
        console.log(errors, fields);
        if (!errors) {
          this.$axios({
            method: "post",
            url: url.check_code,
            params: {
              mobile: this.data.mobile,
              vCode: this.data.code
            }
          })
            .then(res => {
              console.log(res);
              if (res.status === 200 && res.data.status === 1) {
                Toast(`${res.data.msg}请重新输入`);
              } else if (res.status === 200 && res.data.status === 0) {
                this.$axios({
                  method: "post",
                  url: url.register,
                  params: {
                    mobile: this.data.mobile,
                    realName: this.data.name,
                    address: this.data.address,
                    company: this.data.company,
                    password: this.data.password2
                  }
                }).then(res => {
                  console.log(res);
                  if (res.status === 200 && res.data.status === 0) {
                    Toast(res.data.msg); // 等待管理员审核 页面跳转到首页
                    var { ...registerInfo } = res.config.params;
                    // console.log(registerInfo);
                    localStorage.setItem("realName", registerInfo.realName);
                    localStorage.setItem("mobile", registerInfo.mobile);
                    localStorage.setItem("address", registerInfo.address);
                    localStorage.setItem("company", registerInfo.company);
                    localStorage.setItem("password", registerInfo.password);
                    this.$store.commit("userRegisterInfo", registerInfo);
                    this.$router.push("/");
                  } else if (res.status === 200 && res.data.status === 1) {
                    // errors = true;
                    // console.log(errors, fields);
                    // fields.push({message: '该号码已注册', field: 'mobile'});
                    Toast(res.data.msg);
                  }
                });
              }
            })
            .catch(err => {
              Toast(err);
              // console.log(err);
            });
        } else {
          Toast("该号码已注册");
        }
      });
    },
    sendMobileCode() {
      this.validate(errors => {
        if (!errors) {
          Toast("发送成功");
          this.countdown = 60;
          this.countdownSubtract();
        }
      }, "mobile");
      this.$axios({
        method: "post",
        url: url.get_code,
        params: {
          mobile: this.data.mobile
        }
      }).then(res => {
        console.log(res);
        if (res.status === 200 && res.data.status == 0) {
          Toast(res.data.msg);
        }
      });
    },
    countdownSubtract() {
      if (this.countdown > 0) {
        setTimeout(() => {
          this.countdown -= 1;
          this.countdownSubtract();
        }, 1000);
      }
    },

    resetField(attrs) {
      attrs = !attrs
        ? Object.keys(this.errorMsg)
        : Array.isArray(attrs)
        ? attrs
        : [attrs];
      attrs.forEach(attr => {
        this.errorMsg[attr] = "";
      });
    },

    validate(callback, data) {
      this.validator.validate((errors, fields) => {
        this.resetField();
        if (errors) {
          fields.forEach(item => {
            this.errorMsg[item.field] = item.message;
          });
        }
        callback && callback(errors, fields);
      }, data);
    },

    reset() {
      this.data = {
        name: "",
        code: "",
        mobile: "",
        pwd: "",
        password2: "",
        address: "",
        company: ""
      };
      this.validator.setData(this.data);
      this.resetField();
    }
  },
  created() {
    this.validator = validator(this.rules, this.data);
  }
};
</script>
<style lang="less" scoped>
@import "~style/common.less";
.register {
  background-color: @borderColor;
  // background-color: #f00;

  // border: 1px solid red;
  height: calc(100vh - 1.3rem);
  .van-cell-group {
    padding: 0 20px;
  }
}
.register-btn {
  margin-top: 60px;
  display: flex;
  justify-content: space-around;
  button {
    // border:1px solid red;
    height: 0.9rem;
    line-height: 0.9rem;
    // flex-basis: 40%;
    width: 90%;
    padding: 0;
    border-radius: 20px;
  }
  button:first-child {
    transform: translateY(0);
  }
}
.mt10 {
  margin-top: 10px;
}
/deep/ .van-field__button {
  background-color: transparent;
  // border: 1Px solid @priColor;
  padding: 0;
  .van-button {
    border-radius: 16px;
  }
}
/deep/ .van-cell {
  .font-dpr(40px) !important;
}
</style>
